package data

import (
	"context"
	"github.com/go-kratos/kratos/v2/log"
	"go-skeleton/app/admin/service/internal/biz"
	"go-skeleton/app/admin/service/internal/data/ent"
	"go-skeleton/app/admin/service/internal/data/ent/adminrole"
	"go-skeleton/pkg/util/pagination"
)

type AdminRoleRepo struct {
	data *Data
	log  *log.Helper
}

func NewAdminRoleRepo(data *Data, logger log.Logger) biz.AdminRoleRepo {
	return &AdminRoleRepo{
		data: data,
		log:  log.NewHelper(log.With(logger, "module", "data/admin/role")),
	}
}

func (r *AdminRoleRepo) Save(ctx context.Context, ar *ent.AdminRole) (*ent.AdminRole, error) {
	return r.data.db.AdminRole.
		Create().
		SetRoleName(ar.RoleName).
		SetRoleKey(ar.RoleKey).
		SetStatus(ar.Status).
		SetDescribe(ar.Describe).
		SetMenuAuth(ar.MenuAuth).
		SetBtnAuth(ar.BtnAuth).
		Save(ctx)
}

func (r *AdminRoleRepo) Update(ctx context.Context, ar *ent.AdminRole) (*ent.AdminRole, error) {
	return r.data.db.AdminRole.
		UpdateOneID(ar.ID).
		SetRoleName(ar.RoleName).
		SetRoleKey(ar.RoleKey).
		SetStatus(ar.Status).
		SetMenuAuth(ar.MenuAuth).
		SetBtnAuth(ar.BtnAuth).
		Save(ctx)
}

func (r *AdminRoleRepo) FindByID(ctx context.Context, id int64) (*ent.AdminRole, error) {
	return r.data.db.AdminRole.Get(ctx, id)
}

func (r *AdminRoleRepo) FindByKeys(ctx context.Context, keys []string) ([]*ent.AdminRole, error) {
	return r.data.db.AdminRole.Query().Where(adminrole.RoleKeyIn(keys...)).All(ctx)
}

func (r *AdminRoleRepo) List(ctx context.Context, roleName string, pageNum, pageSize int) (roleList []*ent.AdminRole, count int, err error) {
	db := r.data.db.AdminRole.Query()
	count, err = db.Count(ctx)
	if err != nil {
		return
	}

	if count == 0 {
		return
	}

	if roleName != "" {
		db.Where(adminrole.RoleNameContains(roleName))
	}

	if pageNum == 0 {
		pageNum = 1
	}
	roleList, err = db.Order(ent.Asc(adminrole.FieldID)).Offset(pagination.GetPageOffset(pageNum, pageSize)).Limit(pageSize).All(ctx)
	if err != nil {
		return
	}

	return
}

func (r *AdminRoleRepo) ListAll(ctx context.Context) (roleList []*ent.AdminRole, err error) {
	roleList, err = r.data.db.AdminRole.Query().Order(ent.Asc(adminrole.FieldID)).All(ctx)
	if err != nil {
		return
	}

	return
}

func (r *AdminRoleRepo) Del(ctx context.Context, id int64) error {
	return r.data.db.AdminRole.DeleteOneID(id).Exec(ctx)
}
